import { OnQueueFailed, Process, Processor } from '@nestjs/bull';
import { Inject, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Job } from 'bull';
import { Cache } from 'cache-manager';
import { FileService } from '../file/file.service';
import { UserService } from './user.service';
import { getRedisKey, safeOutput } from '../utils';

@Processor('user')
@Injectable()
export class UserQueueConsumer {
    constructor(
        @Inject('CACHE_MANAGER') private cacheManager: Cache,
        private configService: ConfigService,
        private fileService: FileService,
        private userService: UserService,
    ) { }

    /**
     * 新用户信息初始化时，比如首次登录时 处理默认头像转换任务
     */
    @Process('trans-default-avatar')
    async transDefaultAvatar(job: Job) {
        const { user_id, avatar } = job.data;

        // 1. 将头像转存到oss
        const urls = await this.fileService.transToOss([avatar], user_id, false, 'png');
        const url = await this.fileService.moveToDir(urls[0], 'avatar');
        if (!urls || !urls.length || !url) throw new Error(`默认头像上传失败，无图片地址`);

        // 2. 更新数据库
        await this.userService.updateInfoWithCache(user_id, { avatar: url });
    }

    /**
     * 注册时，处理头像移动任务
     */
    @Process('move-avatar')
    async moveAvatar(job: Job) {
        const { user_id, avatar } = job.data;

        // 1. 将头像复制到oss（原头像在oss的temporary文件夹里，定时任务会删除，无需额外处理）
        const url = await this.fileService.moveToDir(avatar, 'avatar');
        if (!url) throw new Error(`头像移动失败，无图片地址`);

        // 2. 更新数据库
        await this.userService.updateInfoWithCache(user_id, { avatar: url });
    }

    /**
     * 队列任务失败处理
     */
    @OnQueueFailed()
    async queueFailed(job: Job, err: any) {
        const { name, attemptsMade, opts, data = {} } = job;

        if (attemptsMade >= opts.attempts) {
            // 所有重试都失败后的处理
            if (['trans-default-avatar', 'move-avatar'].includes(name)) {
                const { user_id } = data || {};
                try {
                    // 使用默认头像作为兜底
                    await this.userService.updateInfoWithCache(user_id, { avatar: 'default_avatar.png' });
                } catch (fallbackError) {
                    console.error('设置默认头像也失败了:', fallbackError);
                }
            }
        }
    }
}